#include "music.h"
#include "ui_music.h"

music::music(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::music)
{
    ui->setupUi(this);

    this->setAttribute(Qt::WA_DeleteOnClose);

    QFile file(":/music.qss"); // 假设style.qss位于资源文件中
    if (file.open(QFile::ReadOnly))
    {
        setStyleSheet(QString(file.readAll())); // 应用全局样式
        file.close();
    }

    setWindowFlag(Qt::FramelessWindowHint,true);//去掉主窗口的边框
    setAttribute(Qt::WA_TranslucentBackground,true);//把主窗口透明

    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished,
            this, &music::replyFinished);

    model = new QStandardItemModel(this);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableView->setFocusPolicy(Qt::NoFocus);
    ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section{background: white; border: 0px solid #E0E0E0;}");

    QStringList list = QStringList()<<"歌名"<<"作家"<<"专辑"<<"时长";
    model->setHorizontalHeaderLabels(list);

    ui->endlineEdit->setEnabled(false);
    ui->boardlineEdit->setEnabled(false);

    flag = true;

     playlist = new QMediaPlaylist;//媒体播放列表
     player = new QMediaPlayer;//媒体播放器
     player->setPlaylist(playlist);//把播放列表设置给播放器

    connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));
    connect(player,SIGNAL(durationChanged(qint64)),this,SLOT(durationChangedSlot(qint64)));

    ui->horizontalSlider->setVisible(false);
}

music::~music()
{
    qDebug()<<"music";
    // delete playlist;
    delete player;
    delete model;
    delete manager;
    delete ui;
}

void music::on_closeButton_clicked()
{
//    mainInterface * m = dynamic_cast<mainInterface *>(this->parent());
//    m->show();
    this->close();
}

void music::mousePressEvent(QMouseEvent *event)
{
    if(false == ui->closeButton->underMouse())
        mouseOff = event->globalPos() - geometry().topLeft();
}

void music::mouseMoveEvent(QMouseEvent *event)
{
    if(false == ui->closeButton->underMouse())
        this->move(event->globalPos() - mouseOff);
}

void music::replyFinished(QNetworkReply *reply)
{
    //    QNetworkRequest::HttpStatusCodeAttribute网址返回的状态码
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute) == 200)
    {
        qDebug()<<"访问服务器成功"<<'\n';
        parseJson(reply->readAll());
    }
}

void music::parseJson(QByteArray byteArray)
{
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    QJsonObject object;
    QJsonArray array;

    QString song,artists,album,duration;
    if(true == doc.isObject()) //JSON是一个对象
    {
        object = doc.object();
        if(true == object.contains("result") && true == object.value("result").isObject()) //doc包含对象"result"字段
        {
            object = object.value("result").toObject();
            if(true == object.contains("songs") && true == object.value("songs").isArray()) //doc对象的"result"对象包含"songs"字段
            {
                array = object.value("songs").toArray();
                for(int i = 0; i < array.size(); i++)
                {
                    if(true == array[i].isObject())
                    {
                        object = array[i].toObject();
                        if(true == object.contains("id")) //歌曲name
                        {
                            unsigned int id = object.value("id").toInt();
                            playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
                        }
                        if(true == object.contains("name") && false == object.value("name").isObject()) //歌曲name
                        {
                            song = object.value("name").toString();
                        }
                        if(true == object.contains("artists") && true == object.value("artists").isArray()) //歌手artists
                        {
                            QJsonArray a = object.value("artists").toArray();
                            for(int j = 0; j < a.size(); j++)
                            {
                                QJsonObject o = a[j].toObject();
                                if(true == o.contains("name") && true == o.value("name").isString())
                                {
                                    artists += o.value("name").toString();
                                    if(j < a.size() - 1) artists += " ";
                                }

                            }
                        }
                        if(true == object.contains("album") && true == object.value("album").isObject()) //专辑album
                        {
                            QJsonObject o = object.value("album").toObject();
                            if(true == o.contains("name") && true == o.value("name").isString())
                            {
                                album = o.value("name").toString();
                            }
                        }
                        if(true == object.contains("duration")) //时长duration
                        {
                            int time = object.value("duration").toInt() / 1000;
                            int min =  time / 60;
                            int sec = time - min * 60;
                            duration = QString("%1:%2").arg(min).arg(sec);
                        }
                    }
                    qDebug()<<i+1<<":歌曲name:"<<song<<"歌手artists:"<<artists<<"专辑album:"<<album<<"时长duration:"<<duration<<'\n';
                    QStandardItem * stand = new QStandardItem(song);
                    stand->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    model->setItem(i, 0, stand);

                    stand = new QStandardItem(artists);
                    stand->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    model->setItem(i, 1, stand);

                    stand = new QStandardItem(album);
                    stand->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    model->setItem(i, 2, stand);

                    stand = new QStandardItem(duration);
                    stand->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
                    model->setItem(i, 3, stand);

                    artists.clear();
                }
            }
        }
    }
    ui->tableView->setModel(model);
}

void music::on_searchPushButton_clicked()
{
    playlist->clear();
    manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").
                                      arg(ui->lineEdit->text()))));

    ui->pausePushButton->setStyleSheet("QPushButton { border-image: url(board.png);}");
    flag = true;

    ui->horizontalSlider->setVisible(false);
    ui->endlineEdit->setVisible(false);
    ui->boardlineEdit->setVisible(false);

}


void music::on_pausePushButton_clicked()
{
    if(false == playlist->isEmpty())
    {
        if(false == flag)
        {
            ui->pausePushButton->setStyleSheet("QPushButton { border-image: url(board.png);}");
            player->pause();
            flag = true;
        }
        else if(true == flag)
        {
            ui->pausePushButton->setStyleSheet("QPushButton { border-image: url(pause.png);}");
            player->play();
            flag = false;
        }
    }
}


void music::on_tableView_doubleClicked(const QModelIndex &index)
{
    ui->horizontalSlider->setVisible(true);
    ui->endlineEdit->setVisible(true);
    ui->boardlineEdit->setVisible(true);

    playlist->setCurrentIndex(index.row());
    player->play();

    ui->pausePushButton->setStyleSheet("QPushButton { border-image: url(pause.png);}");
    flag = false;

    QModelIndex in = model->index(index.row(),3);
    QStringList list = in.data(Qt::DisplayRole).toString().split(':');
    ui->endlineEdit->setText(QString("%1").arg(list[0].toInt(), 2, 10, QLatin1Char('0')) + ':' + QString("%1").arg(list[1].toInt(), 2, 10, QLatin1Char('0')));
}

void music::positionChangedSlot(qint64 position)
{
    qDebug()<<position<<endl;
    ui->horizontalSlider->setValue(position);

    int min = position / 1000 / 60;
    int sec = position / 1000 % 60;
    ui->boardlineEdit->setText(QString("%1").arg(min, 2, 10, QLatin1Char('0')) + ':' + QString("%1").arg(sec, 2, 10, QLatin1Char('0')));
}

void music::durationChangedSlot(qint64 duration)
{
    qDebug()<<"当前歌曲的总时长为"<<duration<<"毫秒"<<endl;
    ui->horizontalSlider->setRange(0,duration);//设置滑块的总范围为歌曲的时长
}

void music::on_horizontalSlider_sliderReleased()
{
    qint64 var = ui->horizontalSlider->value();//得到滑块当前值
    player->setPosition(var);//得到滑块当前值做为音乐播放的当前时间
}

void music::on_nepushButton_clicked()
{
    playlist->next();
    player->play();
    if(false == playlist->isEmpty())
    {
        ui->pausePushButton->setStyleSheet("QPushButton { border-image: url(pause.png);}");
        flag = false;
    }
}

void music::on_prepushButton_clicked()
{
    playlist->previous();
    player->play();
    if(false == playlist->isEmpty())
    {
        ui->pausePushButton->setStyleSheet("QPushButton { border-image: url(pause.png);}");
        flag = false;
    }
}
